package com.ziq.zcamp.manager

import android.os.Handler
import android.os.Looper
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.GsonUtils
import com.gmlive.camp.data.exception.LocalException
import com.ziq.base.extension.launchWithTryAsyncGlobal
import com.ziq.base.manager.MMKVManager
import com.ziq.zcamp.R
import com.ziq.zcamp.api.request.life.MyCampingDataParam
import com.ziq.zcamp.api.request.merchant.MerchantOrderStatisticsByCampParam
import com.ziq.zcamp.api.request.merchant.MerchantOrderStatisticsParam
import com.ziq.zcamp.api.request.merchant.MerchantWelcomeConfigParam
import com.ziq.zcamp.api.respond.merchant.MerchantOrderStatisticsByCampRespond
import com.ziq.zcamp.api.respond.merchant.MerchantOrderStatisticsRespond
import com.ziq.zcamp.api.respond.merchant.MerchantWelcomeConfigRespond
import com.ziq.zcamp.api.service.NetWorkException
import com.ziq.zcamp.api.service.ServiceModule.Companion.onApiFail
import com.ziq.zcamp.api.service.request
import com.ziq.zcamp.bean.merchant.AutoReplyConfig
import com.ziq.zcamp.bean.order.OrderStatisticsResult
import com.ziq.zcamp.bean.user.UserActInfo
import com.ziq.zcamp.bean.user.UserCampInfo
import com.ziq.zcamp.constant.KEY_HISTORY_CITY
import com.ziq.zcamp.constant.KEY_USER_CURRENT_CAMP_INFO
import com.ziq.zcamp.constant.MerchantType
import com.ziq.zcamp.util.BadgeUtil
import dagger.hilt.android.EntryPointAccessors
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.Headers

class MerchantManager private constructor(){

    companion object {
        val instance = SingletonHolder.holder
    }

    private object SingletonHolder {
        val holder= MerchantManager()
    }

    val mHandler = Handler(Looper.getMainLooper())

    //当前切换的营地信息
    val userCurrentCampInfo = MutableLiveData<UserCampInfo?>()
    //单纯活动商户的待接单信息
    val orderStatisticsInfo = MutableLiveData<OrderStatisticsResult?>()
    //商户的所有营地的待接单数等信息,有权限的才显示
    val allCampStatisticsInfo = MutableLiveData<List<OrderStatisticsResult>?>()
    //商户主页是否要更新显示状态
    val merchantUpdateReceivedDisplay = MutableLiveData<Boolean>()
    //当前切换的营地消息配置
    val autoReplyConfig = MutableLiveData<AutoReplyConfig?>()

    /**
     * 获取商户类型
     * 普通用户返回0
     */
    fun obtainMerchantType():Int?{
        return UserManager.instance.userInfo.value?.m_type
    }

    /**
     * 获取活动商户的员工权限信息
     */
    fun obtainMerchantStaffInfo(): UserActInfo?{
        return UserManager.instance.userInfo.value?.act_info
    }


    /**
     * 多营地  保留当前选择营地
     */
    fun updateUserCampInfo(campInfo:UserCampInfo?){
        userCurrentCampInfo.value = campInfo
        autoReplyConfig.value = null
        if(campInfo != null){
            MMKVManager.mmkv.encode(KEY_USER_CURRENT_CAMP_INFO, GsonUtils.toJson(campInfo))
        } else {
            MMKVManager.mmkv.encode(KEY_USER_CURRENT_CAMP_INFO, "")

        }
    }


    /**
     * 商户的订单统计数据
     * 活动商户返回活动订单统计数据
     * 营地商户返回当前切换的营地订单统计数据
     * 如果不是商户返回null
     */
    fun obtainMerchantOrderStatisticsData():OrderStatisticsResult?{
        when(instance.obtainMerchantType()){
            MerchantType.camp.value -> {
                for (item in instance.allCampStatisticsInfo.value?: emptyList()){
                    if (item.campid == instance.userCurrentCampInfo.value?.campid){
                        return item
                    }
                }
                return null
            }
            MerchantType.act.value -> {
                return instance.orderStatisticsInfo.value
            }
            else -> {
                return null
            }
        }
    }

    fun updateOrderStatisticsInfo(item: OrderStatisticsResult?){
        orderStatisticsInfo.postValue(item)
        BadgeUtil.showBadgeNum()
        merchantUpdateReceivedDisplay.postValue(true)
    }


    fun updateAllCampStatisticsInfo(result : List<OrderStatisticsResult>?){
        allCampStatisticsInfo.postValue(result)
        BadgeUtil.showBadgeNum()
        merchantUpdateReceivedDisplay.postValue(true)
    }


    fun getBadgeNum():Int{
        var total = 0
        if (obtainMerchantType() == MerchantType.act.value){
            total = orderStatisticsInfo.value?.total?:0
        }else{
            for (item in allCampStatisticsInfo.value?: emptyList()){
                total += item.total ?: 0
            }
        }
        return total
    }

    /**
     * 根据用户当前的信息获取对应的统计数据
     * 如果用户是活动商户那么返回活动商户的统计信息
     * 如果用户是综合商户那么返回当前切换的camp的统计信息
     */
    fun obtainCurrentStatistics():OrderStatisticsResult?{
        if (obtainMerchantType() == MerchantType.act.value){
            return orderStatisticsInfo.value
        }else{
            if (userCurrentCampInfo.value == null) {
                return null
            }
            for (item in allCampStatisticsInfo.value?: emptyList()){
                if (item.campid == userCurrentCampInfo.value?.campid){
                    return item
                }
            }
            return null
        }
    }

    /**
     * 获取指定营地的待接单统计数据
     */
    fun obtainCurrentStatistics(campid : Int):OrderStatisticsResult?{
        for (item in allCampStatisticsInfo.value?: emptyList()){
            if (item.campid == campid){
                return item
            }
        }
        return null
    }


    /**
     * 判断当前用户除了当前切换的营地是否还有待接单
     * 权限等问题返回false
     */
    fun obtainCurrentUserHaveToBeReceived():Boolean{
        if (obtainMerchantType() == MerchantType.act.value){
            return false
        }else{
            if (userCurrentCampInfo.value == null) {
                return false
            }
            for (item in allCampStatisticsInfo.value?: emptyList()){
                if (item.campid != userCurrentCampInfo.value?.campid && item.receiving_num!=0){
                    return true
                }
                if (item.campid != userCurrentCampInfo.value?.campid && item.act_receiving_num!=0){
                    return true
                }
            }
            return false
        }
    }



}